<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>添加付款管理</title>
<link rel="stylesheet" href="../css/from.css">
<link rel="stylesheet" href="../themes/default/easyui.css">
<link rel="stylesheet" href="../themes/icon.css">
<script src="../js/jquery.min.js"></script>
<script src="../js/jquery.easyui.min.js"></script>
<script src="../js/easyui-lang-zh_CN.js"></script>
<script>
	var company=null;


        //添加非入库单类型的账单paybilldetail
        function addNewPayBillDetail(){
            var row={billCode: "",a: "应付帐目",b: "减少",
                payMoney:"",realMoney:"0",memo: "",operation: ""};
			$("#productList").datagrid("appendRow",row);
		}

        //关闭当前这个页面
        function closeTab(){
            parent.tabsClose();
        }

        //审核方法
        function payCurrentPayBill(){
            $.messager.confirm('确认','您确认想要审核吗？',function(r){
                if (r){
                	//自动设置表单日期为今天
                    /*$("#addDate").datebox('setValue','yyyy-mm-dd');*/
                    $.ajax({
                    	url: "../../payBillController/payCurrentPayBill",
                    	dataType: "json",
                    	success: function(data){
                    		if(data.result=='noPower'){
                    			alert("没有权限！");
                    		}else{
                    			if ($("#savePayBill_btn").attr('title')=="save"){
                        			$.ajax({
                           				url: "../../payBillController/payCurrentPayBill",
                            			data: {code:$("#code").val()},
                            			dataType:"text",
                            			success:function(data){
                                			alert(data);
                                			$.ajax({
                                    			url: "../../payBillController/findPayBill",
                                    			data:{payCode:$("#code").val()},
                                    			dataType: "text",
                                    			success: function (data) {
                                        			window.location.href="paybill_detail_checked.html";
                                    			}
                                			});
                            			}
                        			});
								} else{
                        			$('#form1').form('submit', {
                            			url: "../../payBillController/addPayBill",
                            			success:function(data){
                                			//保存paybilldetail的ajax
                                			var rows=$("#productList").datagrid("getRows");
                                			if (rows.length!=0){
                                    			$.ajax({
                                        			url: "../../payBillController/savePayBillDetailToDataBase",
                                        			data: {saveRows: JSON.stringify(rows),
                                            			payCode: $("#code").val(),
                                            			payData: $("#addDate").datebox("getText"),
                                            			payType: $("#contacter").combobox("getValue"),
                                            			payTotalMoney: $("#type").textbox('getText'),
                                            			memo: $("#fax").textbox("getText")},
                                        			dataType: "text",
                                        			success: function(data){
                                            			if(data=="success"){
                                                			$.ajax({
                                                    			url: "../../payBillController/payCurrentPayBill",
                                                    			data: {code:$("#code").val()},
                                                    			beforeSend:function(){
                                                        			return true;
                                                    			},
                                                    			dataType:"text",
                                                   				success:function(data){
                                                        			alert(data);
                                                        			$.ajax({
                                                            			url: "../../payBillController/findPayBill",
                                                            			data:{payCode:$("#code").val()}
                                                        			});
                                                        			window.location.href="paybill_detail_checked.html";
                                                    			}
                                                			});
                                            			}
                                        			},
                                        			error: function(){
                                            			return false;
                                        			}
                                    			});
                                    			/*parent.tabsClose();*/
                                			} else{
                                    			alert("没有需要保存的入库单")
                                			}
                            			}
                        			});
								}
                    		}
                    	}
                    });
                }
            });

        }

        //保存方法
        function savePayBillDetailToDataBase(){
            if (!$("#addDate").datebox('isValid')){
                alert("请输入正确的时间");
                return false;
            }else if (!$("#supplierName").textbox('isValid')){
                alert("请填写供应商")
			} else{
                //生成paybill的ajax
                $('#form1').form('submit', {
                    url: "../../payBillController/addPayBill",
                    success:function(data){
                    	if(data=='noPower'){
                    		alert("没有权限");
                    	}else{
                    		//保存paybilldetail的ajax
                        	var rows=$("#productList").datagrid("getRows");
                        	if (rows.length!=0){
                            	$.ajax({
                                	url: "../../payBillController/savePayBillDetailToDataBase",
                                	data: {saveRows: JSON.stringify(rows),
                                    	payCode: $("#code").val(),
                                    	payData: $("#addDate").datebox("getText"),
                                    	payType: $("#contacter").combobox("getValue"),
                                    	payTotalMoney: $("#type").textbox('getText'),
                                    	memo: $("#fax").textbox("getText")},
                                	dataType: "text",
                                	success: function(data){
                                    	if(data=="success"){
                                        	alert("保存成功");
                                        	return true;
                                    	}
                                	},
                                	error: function(){
                                    	return false;
                                	}
                            	});
                            	parent.tabsClose();
                        	} else{
                            	alert("没有需要保存的入库单")
                        	}
                    	}
                    }
                });
                alert("保存成功！");
                $("#savePayBill_btn").attr("disabled", true);
                $("#savePayBill_btn").attr("title", "save");
                return true;
            }
        }

        //删除instroagebill的一行数据，删除后重置datagrid
        function deleteInstroageBillInRow(index){
            var rows=$("#productList").datagrid('getRows');
            var a=parseFloat($("#type").textbox('getValue'));
            var b=rows[index].payMoney;
            if (b!=null ||b!=undefined ||b!=""){
                var curMoney=a-b;
                $("#type").textbox('setValue',curMoney);
                $("#productList").datagrid('deleteRow',index);
                rows=$("#productList").datagrid('getRows');
                $("#productList").datagrid('loadData',rows);
			}
        }

        //从未选择的introagebill选择一个添加
        function addInstroageBillTopaybill(){
            var selectRows=$("#instroagebill").datagrid("getSelections");
            var rows=$("#productList").datagrid("getRows");
            if(selectRows==null||selectRows==""){
                alert("请选择入库单！");
                return false;
            }
            var flag=false;
            if(rows!=null||rows!=""){
                for(var i=0;i<selectRows.length;i++){
                    for(var j=0;j<rows.length;j++){
                        if(rows[j].billCode==selectRows[i].code){
                            flag=true;
                        }
                    }
                }
                if(flag==false){
                    for(var i=0;i<selectRows.length;i++){
                        var addrow={billCode: selectRows[i].code,a: "应付帐目",b: "减少",
                            payMoney:selectRows[i].money,realMoney:0,memo: selectRows[i].memo,operation: ""};
                        $("#productList").datagrid('appendRow',addrow);
                        var curMoney=parseFloat($("#type").textbox('getValue'))+selectRows[i].money;
                        $("#type").textbox('setValue',curMoney);
                    }
                }else{
                    alert("请不要选择重复入库单！");
                    $("#instroagebill").datagrid("clearSelections");
                    $("#instroagebill").datagrid("clearChecked");
                    return false;
                }
            }else{
                for(var i=0;i<selectRows.length;i++){
                    var addrow={billCode: selectRows[i].code,a: "应付帐目",b: "减少",
                        payMoney:selectRows[i].money,realMoney:0,memo: selectRows[i].memo,operation: ""};
                    $("#productList").datagrid('appendRow',addrow);
                    var curMoney=parseFloat($("#type").textbox('getValue'))+selectRows[i].money;
                    $("#type").textbox('setValue',curMoney);
                }
            }
            $("#win").window('close');
        }

        //加载paybill的入库单
        function searchInstroageBill(){
            var json = {
                findcode: $("#findcode_I").val(),
                findstartDate: $("#findstartDate_I").val(),
                findendDate: $("#findendDate_I").val(),
                findsupplierName: $("#findsupplierName_I").val()
            };
            loadInstroageListByPayBill(json);

        }

        //重置instroagebill面板的查找表单
        function resetForm(){
            $("#form3").form('reset');
            $("#form3").form('load',{
                findsupplierName_I: $("#supplierName").val()
            });
        }

        //加载paybill的instroagebill 的datagrid方法
        function loadInstroageListByPayBill(params){
            $("#instroagebill").datagrid({
                fit: true,
                url:'../../payBillController/loadUnselectedInstroageBill',
                toolbar:'#instroageToolbar',
                rownumbers:true,
                checkOnSelect:true,
                columns:[[
                    {field: "ck",checkbox:true},
                    {field:'code',title:'入库单号'},
                    {field: "customName",title: "供应商名"},
                    {field: "instroageDate",title: "入库日期",formatter: function (value,row,index) {
                            var date=new Date(value).toLocaleDateString().replace(/\//g,'-');
                            return date;
                        }},
                    {field:'money',title:'应付金额'},
                    {field:'payStatus',title:'实付金额',formatter:function(value,row,index){
                            if(value==1){
                                return "0.00";
                            }else if(value==2){
                                return row.money;
                            }
                        }},
                    {field:'memo',title:'备注'}
                ]],
                pagination: true,//向后台传递参数page 和rows
                pageNumber: 1,
                pageSize: 5,
                pageList: [5,10,20],
                queryParams: params

            });
        }

        //关闭instroagebill面板
        function closeInstroageField(){
            $("#win").window('close');
        }

        //从面板添加一个未选择的instroagebill到paybill的instroagebill
        function addNewInstroageBill(){
            if ($("#supplierName").val()==null || $("#supplierName").val()==''){
                alert("请选择供应商！");
                loadSupplier();
			} else{
                $("#win").window('open');
                $("#form3").form('load',{
                    findsupplierName_I: $("#supplierName").val()
                });
                $("#findsupplierName_I").textbox({readonly: true});
                loadInstroageListByPayBill({findsupplierName: $("#supplierName").val()});
			}
        }

        function loadDataGrid_company(params){
            $("#dataGrid_company").datagrid({
                fit:true,
                url:'../../payBillController/companyPayBill',
                rownumbers:true,
                checkOnSelect:false,
                columns:[[
                    {field:'code',title:'供应商代号'},
                    {field:'name',title:'供应商名称'},
                    {field:'type',title:'类型',formatter:function(value){
                            if(value==1){
                                return "客户";
                            }else if(value==2){
                                return "供应商";
                            }
                        }},
                    {field:'linkman',title:'联系人'},
                    {field: "phone",title: "电话"},
                    {field: "fax",title: "传真"},
                    {field: "address",title: "地址"}
                ]],
                toolbar:'#searchdiv',
                queryParams: params,
                pagination:true ,//向后台传递参数page 和rows
                pageNumber: 1,
                pageSize: 5,
                pageList: [5,10,20],
                onDblClickRow: function(index, row){
                    company=row.name;
                    $('#win1').window('close');
                    $("#form2").form("reset");
                    $("#supplierName").textbox({value:company});
                    var datagrid_length=$("#productList").datagrid('getRows').length;
                    for (var i=0;i<datagrid_length;i++){
                        deleteInstroageBillInRow(0);
					}

                }
            });
		}

        function searchCompany(){
            var params={"name":$("#findcode1").val(),"code":$("#findendDate1").val(),"type":$("#companyType").val()};
            loadDataGrid_company(params);
        }
        function loadSupplier() {
            loadDataGrid_company(null);
            $('#win1').window('open');
        }


        $(function(){
            $.extend($.fn.validatebox.defaults.rules, {
                end: {
                    validator: function (value, param) {
                        var curDate=new Date();
                        var startTmp=new Date(curDate.toLocaleDateString());
                        var endTmp = new Date(value.replace(/-/g, "/"));
                        return /*startTmp <= endTmp*/ true;
                    },
                    message: '日期不能选择当前日期（今日）之前'
                }
            });

            $.extend($.fn.datagrid.defaults.editors, {
                numberbox: {
                    init: function(container, options){
                        var input = $('<input type="number" class="datagrid-editable-input">').appendTo(container);
                        return input;
                    },
                    getValue: function(target){
                        return $(target).val();
                    },
                    setValue: function(target, value){
                        $(target).val(value);
                    },
                    resize: function(target, width){
                        var input = $(target);
                        if ($.boxModel == true){
                            input.width(width - (input.outerWidth() - input.width()));
                        } else {
                            input.width(width);
                        }
                    }
                }
            });

            $.extend($.fn.datagrid.defaults.editors, {
                text: {
                    init: function(container, options){
                        var input = $('<input type="text" class="datagrid-editable-input">').appendTo(container);
                        return input;
                    },
                    getValue: function(target){
                        return $(target).val();
                    },
                    setValue: function(target, value){
                        $(target).val(value);
                    },
                    resize: function(target, width){
                        var input = $(target);
                        if ($.boxModel == true){
                            input.width(width - (input.outerWidth() - input.width()));
                        } else {
                            input.width(width);
                        }
                    }
                }
            });

            $.extend($.fn.datagrid.methods, {
                editCell: function(jq,param){
                    return jq.each(function(){
                        var opts = $(this).datagrid('options');
                        var fields = $(this).datagrid('getColumnFields',true).concat($(this).datagrid('getColumnFields'));
                        for(var i=0; i<fields.length; i++){
                            var col = $(this).datagrid('getColumnOption', fields[i]);
                            col.editor1 = col.editor;
                            if (fields[i] != param.field){
                                col.editor = null;
                            }
                        }
                        $(this).datagrid('beginEdit', param.index);
                        for(var i=0; i<fields.length; i++){
                            var col = $(this).datagrid('getColumnOption', fields[i]);
                            col.editor = col.editor1;
                        }
                    });
                }
            });


            /*初始化已选择入库表格*/
            /* 初始化数据表格 */
            $("#productList").datagrid({
                fit:true,
                /* rownumbers:true, */
                checkOnSelect:false,
                singleSelect: true,
                rownumbers: true,
                toolbar: '#form_field',
                onSelect:function(rowIndex, rowData){  //用于解决点击某行不会高亮
                    $('#productList').datagrid('unselectRow',rowIndex);
                },
                columns:[[
                    {field:'billCode',title:'业务单号',width: 122},
                    {field: "a",title: "本方账目",width: 100,formatter: function (value,row,index) {
                            return "应付帐目";
                        }},
                    {field: "b",title: "本方增减",width: 100,formatter: function (value,row,index) {
                            return "减少";
                        }},
                    {field:'payMoney',title:'应付金额',width: 100,editor: 'numberbox'},
                    {field:'realMoney',title:'实付金额',width: 100},
                    {field:'memo',title:'备注',editor: 'text',width: 100},
                    {field: "operation",title: "操作",width: 100,formatter:function(value,row,index){
                            return "<a id='a_id_"+index+"' href='#' onclick='deleteInstroageBillInRow("+index+")'>删除</a>";
                        }}
                ]],
                onClickCell: function(index, field, value){
                    var rows=$('#productList').datagrid('getRows');
                    var billcode=rows[index].billCode;
                    if (billcode==null ||billcode==""){
                        //减去要编辑的数量
                        if (field =='payMoney') {
                            //写入payMoney
							if (value!=''){
                                var curMoney=parseFloat($("#type").textbox('getValue'))-parseFloat(value);
                                $("#type").textbox('setValue',curMoney);
							}
                        }
                        $("#productList").datagrid('selectRow',index).datagrid('editCell',{index: index,field: field});
                        var editor = $('#productList').datagrid('getEditor', {index:index,field: field});
                        editor.target.focus();
                        editor.target.bind('blur', function () {
                            if (field =='payMoney') {
                                var value_e=editor.target.val();
                                if (value_e!=''){
                                    var curMoney1=parseFloat($("#type").textbox('getValue'))+parseFloat(value_e);
                                    $("#type").textbox('setValue',curMoney1);
                                }
                            }

                            //写入payMoney
                            $('#productList').datagrid('endEdit', index);
                        });
					}else{
                        if (field =='memo') {
                            $("#productList").datagrid('selectRow',index).datagrid('editCell',{index: index,field: field});
                            var editor = $('#productList').datagrid('getEditor', {index:index,field: field});
                            editor.target.focus();
                            editor.target.bind('blur', function () {
                                $('#productList').datagrid('endEdit', index);
                            });
                        }
					}
           		 }
            });

            /*供应商弹窗设置*/
            $('#win1').window({
                width:800,
                height:400,
                modal:true,
                title:"请选择 供应商 温馨提示：双击选择供应商",
                onBeforeClose:function(){
                    $("#form2").form("reset");
                    return true;
                }
            });

            $('#win1').window('close');
            $('#form1').form('load','../../payBillController/beforeAddPayBill');
            $("#code").textbox('readonly',true);
            $("#code").textbox('textbox').css('background','#CCCCCC');
            $("#supplierName").textbox('readonly',true);
            $("#type").textbox('readonly',true);
            $("#type").textbox('setValue',0.00);
            $("#contacter").combobox({editable:false});
			/*入库单弹窗设置*/
            $("#win").window({
                onResize: function(width, height){
                    $("#instroageField").height(($("#win").height()-30));
                },
                onBeforeOpen:function(){
                    $("#instroageField").height(($("#win").height()-30));
                },
                onBeforeOpen:function(){
                    $("#form3").form('reset');
                    loadInstroageListByPayBill(null);
                }
            });
            $("#win").window('close');
            /* 入库单弹窗textbox */
            $("#findcode_I").textbox({
                width: '100px'
            });
            $("#findsupplierName_I").textbox({
                width: '200px'
            });
            $("#findstartDate_I").datebox({
                width: '120px'
            });
            $("#findendDate_I").datebox({
                width: '120px'
            });
		});
</script>
<style>
body {
	font-size: 12px;
	padding: 10px
}

.l-table-edit {
	border-collapse: collapse;
	border-spacing: 0;
}

.l-table-edit-td {
	padding: 4px;
	font-size: 12px;
	border: 1px solid #84a0c4
}
</style>


</head>
<body>
	<div id="form_field" style="background-color: white;">
		<form name="form1" id="form1" action="" method="post">
			<table cellpadding="0" cellspacing="0" class="l-table-edit"
				style="width: 100%">
				<tr>
					<td width="17%" align="right" class="l-table-edit-td">付款单号：</td>
					<td width="27%" align="left" class="l-table-edit-td"><input
						class="easyui-textbox" name="code" type="text" id="code" size="30"
						maxlength="100" ltype="text" style="height:20px" />
					</td>
					<td width="13%" align="right" class="l-table-edit-td">付款日期：</td>
					<td width="43%" align="left" class="l-table-edit-td"><input
						class="easyui-datebox" type="text" id="addDate"
						data-options="required:true,validType:['end']" name="payDate"
						style="height:20px" />
					</td>
				</tr>
				<tr>
					<td width="17%" align="right" class="l-table-edit-td"><a
						href="#" onclick="loadSupplier()">供应商：</a>
					</td>
					<td align="left" class="l-table-edit-td"><input
						class="easyui-textbox" type="text" id="supplierName" value=""
						style="height:20px" size="30" maxlength="100" ltype="text"
						name="customName" data-options="required:true" />
					<td width="13%" align="right" class="l-table-edit-td">付款方式：</td>
					<td align="left" class="l-table-edit-td"><select
						class="easyui-combobox" name="payType" id="contacter"
						style="width: 160px;height:20px">
							<option value="1">现金</option>
							<option value="2">转账</option>
					</select>
					</td>
				</tr>
				<tr>
					<td width="17%" align="right" class="l-table-edit-td">付款金额：</td>
					<td align="left" class="l-table-edit-td"><input
						class="easyui-textbox" type="text" id="type" value="" size="30"
						maxlength="50" ltype="text" name="payTotalMoney"
						style="height:20px" />
					</td>
					<td width="17%" align="right" class="l-table-edit-td">备注：</td>
					<td align="left" class="l-table-edit-td"><input type="text"
						class="easyui-textbox" id="fax" value="" maxlength="50"
						ltype="text" name="memo" style="height:20px" />
					</td>
				</tr>

			</table>
		</form>
		<br> <input type="button" value="新      增"
			style="cursor:pointer;width: 60px" disabled="disabled"> <input
			type="button" value="选入库单" style="cursor:pointer;width: 60px"
			onclick="addNewInstroageBill()"> <input type="button"
			value="新增应付" style="cursor:pointer;width: 60px"
			onclick="addNewPayBillDetail()"> <input id="savePayBill_btn"
			type="button" value="保      存" style="cursor:pointer;width: 60px"
			onclick="savePayBillDetailToDataBase()">&ensp; <input
			type="button" value="审      核" style="cursor:pointer;width: 60px"
			onclick="payCurrentPayBill()">&ensp; <input type="button"
			value="撤销审核" style="cursor:pointer;width: 60px" disabled="disabled">&ensp;
		<input type="button" value="打     印"
			style="cursor:pointer;width: 60px" onclick="">&ensp; <input
			type="button" value="关     闭" style="cursor:pointer;width: 60px"
			onclick="closeTab()">&ensp;
		<div style="display: block; height: 14px"></div>
	</div>
	<div id="productList" class="easyui-datagrid"></div>
	<div id="win1">
		<div id="dataGrid_company" class="easyui-datagrid">
			<div id="searchdiv" style="display: block; width: 100%;">
				<form name="form2" id="form2">
					<table width="100%" border="0" cellspacing="0"
						style="background-color: #c9dfff;">
						<tbody>
							<tr>
								<td width="70"><b>检索条件:</b>
								</td>
								<td width="70" align="right">单位名称:</td>
								<td width="150" align="left"><input name="findcode"
									type="text" id="findcode1" maxlength="100">
								</td>
								<td width="70" align="right">单位代号:</td>
								<td width="150" align="left"><div class="l-text-wrapper">
										<div class="l-text l-text-date">
											<input name="findendDate" type="text" id="findendDate1"
												value="" maxlength="30" ligeruiid="findendDate">
										</div>
									</div>
								</td>
								<td width="70" align="right">单位类别:</td>
								<td width="150" align="left"><select id="companyType">
										<option value="">请选择</option>
										<option value="1">客户</option>
										<option value="2">供应商</option>
								</select></td>
								<td width="72"><a id="search_btn" href="#"
									class="easyui-linkbutton" data-options="iconCls:'icon-search'"
									onclick="searchCompany()">搜索</a></td>
							</tr>
						</tbody>
					</table>
					<input type="hidden" id="menuCode" value="100001001">
				</form>
			</div>
		</div>
	</div>
	<div id="win" class="easyui-window easyui-layout" title="请选择 入库单"
		style="width: 1000px; height: 350px"
		data-options="iconCls:'icon-save',modal:true">

		<div id="instroageField">
			<div id="instroageToolbar">
				<form name="form3" id="form3">
					<table width="100%" border="0" cellspacing="0"
						style="background-color: #c9dfff;">
						<tbody>
							<tr>
								<td width="70"><b>检索条件:</b>
								</td>
								<td width="70" align="right">入库单号:</td>
								<td width="110" align="left"><input name="findcode"
									class="easyui-textbox" type="text" id="findcode_I">
								</td>
								<td width="70" align="right">开始日期:</td>
								<td width="110" align="left"><input name="findstartDate"
									type="text" id="findstartDate_I" class="easyui-datebox">
								</td>
								<td width="70" align="right">结束日期:</td>
								<td width="110" align="left"><input name="findendDate"
									type="text" id="findendDate_I" class="easyui-datebox">
								</td>
								<td width="70" align="right">供应商名:</td>
								<td width="110" align="left"><input
									name="findsupplierName_I" class="easyui-textbox" type="text"
									id="findsupplierName_I">
								</td>
								<td width="72"><a id="search_btn_I" href="#"
									class="easyui-linkbutton" data-options="iconCls:'icon-search'"
									onclick="searchInstroageBill()">搜索</a>
								</td>
								<td width="72"><a id="reset_btn" href="#"
									class="easyui-linkbutton" data-options="iconCls:'icon-refresh'"
									onclick="resetForm()">重置</a>
								</td>
								<td width="0"></td>
							</tr>
						</tbody>
					</table>
				</form>
			</div>
			<div id="instroagebill" class="easyui-datagrid"></div>
		</div>
		<div id="instroagebill_btn" class=""
			style="height: 30px; width: 100%; display: table; line-height: 30px;">
			<div style="float: right; line-height: 30px;">
				<input type="button" value="退出"
					style="float: right; display: inline-block; vertical-align: middle; margin: 4px;cursor:pointer;"
					onclick="closeInstroageField()">&ensp;&ensp; <input
					type="button" value="添加入库单"
					style="float: right; display: inline-block; vertical-align: middle; margin: 4px;cursor:pointer;"
					onclick="addInstroageBillTopaybill()">&ensp;&ensp;
			</div>
		</div>
	</div>
</body>
</html>